<template>
    <el-dialog :title="title" :visible.sync="dialogVisible" @open="openDialog" @close="closeDialog" append-to-body
        fullscreen>
        <div class="cropper-content">
            <div class="cropper-box" v-show="step1">
                <div class="cropper">
                    <vue-cropper ref="cropper" :img="option.img" :outputSize="option.outputSize"
                        :outputType="option.outputType" :info="option.info" :canScale="option.canScale"
                        :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth"
                        :autoCropHeight="option.autoCropHeight" :fixed="option.fixed" :fixedNumber="option.fixedNumber"
                        :full="option.full" :fixedBox="option.fixedBox" :canMove="option.canMove"
                        :canMoveBox="option.canMoveBox" :original="option.original" :centerBox="option.centerBox"
                        :height="option.height" :infoTrue="option.infoTrue" :maxImgSize="option.maxImgSize"
                        :enlarge="option.enlarge" :mode="option.mode" @realTime="realTime" @imgLoad="imgLoad">
                    </vue-cropper>
                </div>
                <!--底部操作工具按钮-->
                <div class="footer-btn">
                    <div class="scope-btn">
                        <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);"
                            accept="image/png, image/jpeg, image/gif, image/jpg" @change="selectImg($event)">
                        <el-button size="mini" type="danger" plain icon="el-icon-zoom-in"
                            @click="changeScale(1)">放大</el-button>
                        <el-button size="mini" type="danger" plain icon="el-icon-zoom-out"
                            @click="changeScale(-1)">缩小</el-button>
                        <el-button size="mini" type="danger" plain @click="rotateLeft">左旋转</el-button>
                        <el-button size="mini" type="danger" plain @click="rotateRight">右旋转</el-button>
                    </div>
                    <div class="upload-btn">
                        <el-button size="mini" type="success" @click="nextStep('blob')">下一步 <i
                                class="el-icon-upload"></i></el-button>
                    </div>
                </div>
            </div>
            <!--预览效果图-->
            <!-- <div class="show-preview">
                <div :style="previews.div" class="preview">
                    <img :src="previews.url" :style="previews.img">
                </div>
            </div> -->
            <div class="cropper-box warp" v-show="step2">
                <div class="cropper">
                    <div class="preview" style="height: fit-content;">
                        <canvas id="canvas" @touchstart="uploadScaleStart" @touchmove="uploadScaleMove"
                            @mousedown="mouseDown" @mousemove="mouseMove" @mouseup="mouseUp" />
                        <canvas id="canvasReal" style="display: none;"/>
                    </div>
                    <vue-slider ref="slider3" v-bind="slider" v-model="slider.value" :process="false">
                        <template slot="label" slot-scope="{ label, active }">
                            <span :class="['custom-label', { active }]" v-if="label % 10 === 0">
                                橡皮擦尺寸：{{ label }}
                            </span>
                        </template>
                    </vue-slider>
                    <div class="upload-btn">
                        <el-button size="mini" type="success" @click="uploadImg('blob')">上传封面 <i
                                class="el-icon-upload"></i></el-button>
                    </div>
                </div>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import { VueCropper } from 'vue-cropper'
import request from '@/utils/request';
import VueSlider from 'vue-slider-component';
import 'vue-slider-component/theme/default.css'

export default {
    data() {
        return {
            title: "选择AI编辑的图片",
            canvasLeft: 0,
            canvasTop: 0,
            ctx: '',
            startX: null,
            startY: null,
            canvasWidth: 0,
            canvasHeight: 0,
            selectColor: 'black',
            lineColor: '#1A1A1A', // 颜色
            lineSize: 5, // 笔记倍数
            step1: true,
            step2: false,
            title: "编辑图片",
            dialogVisible: false,
            instance: null, previews: {},
            option: {
                img: '',             //裁剪图片的地址
                outputSize: 1,       //裁剪生成图片的质量(可选0.1 - 1)
                outputType: 'png',  //裁剪生成图片的格式（jpeg || png || webp）
                info: true,          //图片大小信息
                canScale: true,      //图片是否允许滚轮缩放
                autoCrop: true,      //是否默认生成截图框
                autoCropWidth: 512,  //默认生成截图框宽度
                autoCropHeight: 512, //默认生成截图框高度
                fixed: true,         //是否开启截图框宽高固定比例
                fixedNumber: [1, 1], //截图框的宽高比例
                full: false,         //false按原比例裁切图片，不失真
                fixedBox: false,      //固定截图框大小，不允许改变
                canMove: false,      //上传图片是否可以移动
                canMoveBox: true,    //截图框能否拖动
                original: false,     //上传图片按照原始比例渲染
                centerBox: false,    //截图框是否被限制在图片里面
                height: true,        //是否按照设备的dpr 输出等比例图片
                infoTrue: false,     //true为展示真实输出图片宽高，false展示看到的截图框宽高
                maxImgSize: 1024,    //限制图片最大宽度和高度
                enlarge: 1,          //图片根据截图框输出比例倍数
                mode: '100vh 100vh'  //图片默认渲染方式
            },
            slider: {
                width: '100%',
                show: true,
                value: 5,
                min: 5,
                max: 100,
                piecewiseLabel: true,
                tooltip: 'always',
                tooltipDir: [
                    "bottom",
                    "top"
                ],

            }
        };
    },
    components: {
        VueCropper,
        VueSlider
    },
    props: ['Name'],
    methods: {
        openDialog() {
            let that = this;
        },
        closeDialog() {
            Object.assign(this.$data, this.$options.data());
        },
        //初始化函数
        imgLoad(msg) {
            console.log("工具初始化函数=====" + msg);
            let canvas = document.getElementById("canvas");
            this.ctx = canvas.getContext('2d');
            let canvasReal = document.getElementById("canvas");
            this.ctxReal = canvasReal.getContext('2d');
        },
        //图片缩放
        changeScale(num) {
            num = num || 1
            this.$refs.cropper.changeScale(num)
        },
        //向左旋转
        rotateLeft() {
            this.$refs.cropper.rotateLeft()
        },
        //向右旋转
        rotateRight() {
            this.$refs.cropper.rotateRight()
        },
        //实时预览函数
        realTime(data) {
            this.previews = data;
            //this.canvas = canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        },

        //上传图片
        uploadImg() {
            let that = this;
            let canvas = document.getElementById("canvas");
            canvas.toBlob(
                async (data) => {
                    let param = new FormData();
                    param.append('file', data, "new.png")
                    let config = {
                        headers: { 'Content-Type': 'multipart/form-data' }
                    };
                    request.post('/p/msg/uploadImg', param, config).then(() => {
                        let contact = this.$parent.$refs.IMUI.getCurrentContact();
                        let msg = {
                            id: this.$parent.generateRandId(),
                            status: "succeed",
                            type: "image",
                            sendTime: new Date().getTime(),
                            content: URL.createObjectURL(data),
                            toContactId: contact.id,
                            fromUser: contact,
                        };
                        this.$parent.appendMessage(msg);
                        msg = {
                            id: this.$parent.generateRandId(),
                            status: "succeed",
                            type: "text",
                            sendTime: new Date().getTime(),
                            content: "已经将图片上传到画板，请描述希望大叔填充的内容",
                            toContactId: contact.id,
                            fromUser: contact,
                        };
                        this.$parent.appendMessage(msg);
                        that.dialogVisible = false;
                    }
                    );
                });
        },

        nextStep(type) {
            let _this = this;
            this.title = "擦除要重绘的区域";
            if (type === 'blob') {
                //获取截图的blob数据
                this.$refs.cropper.getCropBlob(async (data) => {
                    this.step1 = false;
                    this.step2 = true;
                    let img = new Image();
                    img.onload = () => {
                        //在假图上画
                        //假图最大尺寸 
                        let maxWidth = document.documentElement.clientWidth-20;
                        let maxHeight = document.documentElement.clientHeight-145;
                        let scale = maxWidth/img.width > maxHeight/img.height ? maxHeight/img.height : maxWidth/img.width;
                        let canvas = document.getElementById("canvas");
                        canvas.width = img.width * scale;
                        canvas.height = img.height * scale;
                        this.canvasLeft = canvas.getBoundingClientRect().x;
                        this.canvasTop = canvas.getBoundingClientRect().y;
                        let ctx = this.ctx;
                        ctx.scale(scale,scale);
                        ctx.drawImage(img, 0, 0);
                        ctx.scale(1/scale,1/scale);


                        //真图 真图先不玩了啊
                        let canvasReal = document.getElementById("canvasReal");
                        canvasReal.width = img.width;
                        canvasReal.height = img.height;
                        this.canvasRealLeft = canvas.getBoundingClientRect().x;
                        this.canvasRealTop = canvas.getBoundingClientRect().y;
                        

                        



                        // ctx.font = "10px 幼圆";
                        // // 创建渐变
                        // var gradient = ctx.createLinearGradient(0, 0, 200, 0);
                        // gradient.addColorStop("0", "magenta");
                        // gradient.addColorStop("0.5", "blue");
                        // gradient.addColorStop("1.0", "red");

                        // // 用渐变填色
                        // ctx.fillStyle = gradient;
                        // ctx.fillText("曹凡可修", 5, 10);
                    };
                    img.src = URL.createObjectURL(data);
                })
            }
        },
        mouseDown(e) {
            console.log(e);
            this.md = true;
            this.uploadScaleStart(e);
        },
        mouseUp(e) {
            this.md = false;
        },
        mouseMove(e) {
            if (this.md) {
                console.log(e);
                this.uploadScaleMove(e);
            }
        },
        // 笔迹开始
        uploadScaleStart(e) {
            console.log("beginpath");
            this.startX = e.touches ? e.touches[0].clientX : e.x - this.canvasLeft;
            this.startY = e.touches ? e.touches[0].clientY : e.y - this.canvasTop;
            //设置画笔参数
            //画笔颜色
            //this.ctx.strokeStyle = "transparent";
            //this.ctx.strokeStyle="green";
            //this.ctx.strokeStyle=("rgba(0,0,0,90)");
            //设置线条粗细
            this.ctx.lineWidth = this.$refs.slider3.getValue();
            //设置线条的结束端点样式
            this.ctx.lineCap = "round";
            //开始画笔
            this.ctx.beginPath()
        },
        // 笔迹移动
        uploadScaleMove(e) {
            console.log(e);
            this.ctx.globalCompositeOperation = "destination-out";
            //取点
            let temX = e.touches ? e.touches[0].clientX : e.x - this.canvasLeft;
            let temY = e.touches ? e.touches[0].clientY : e.y - this.canvasTop;
            //画线条
            this.ctx.moveTo(this.startX, this.startY);
            this.ctx.lineTo(temX, temY);
            this.ctx.stroke();
            this.startX = temX
            this.startY = temY
            this.ctx.draw = true;
        },
        sliderChange(e) {
            console.log('value 发生变化：' + e.detail.value)
            this.lineSize = e.detail.value
        },/**
             * 重写
             */
        retDraw() {
            this.ctx.clearRect(0, 0, 700, 730);
            this.ctx.draw();
            //设置canvas背景
            this.ctxcanvas();
            //    this.setCanvasBg('#fff');
        },
        /**
         * @param {Object} str
         * @param {Object} color
         * 选择颜色
         */
        selectColorEvent(str, color) {
            this.selectColor = str;
            this.lineColor = color;
        },
    },

}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
    padding: 10px !important;
    height: calc(100vh - 55px);
    overflow-y: auto;
}

.cropper-content {
    display: flex;
    display: -webkit-flex;
    justify-content: flex-end;

    .cropper-box {
        flex: 1;
        width: 100%;

        .cropper {
            width: auto;
            height: calc(100vh - 150px);
        }
    }

    .show-preview {
        flex: 1;
        -webkit-flex: 1;
        display: flex;
        display: -webkit-flex;
        justify-content: center;

        .preview {
            overflow: hidden;
            border: 1px solid #67c23a;
            background: #cccccc;
            position: relative;
        }
    }
}

.footer-btn {
    margin-top: 30px;
    display: flex;
    display: -webkit-flex;
    justify-content: flex-end;

    .scope-btn {
        display: flex;
        display: -webkit-flex;
        justify-content: space-between;
        padding-right: 10px;
    }

    .upload-btn {
        flex: 1;
        -webkit-flex: 1;
        display: flex;
        display: -webkit-flex;
        justify-content: center;
    }

    .btn {
        outline: none;
        display: inline-block;
        line-height: 1;
        white-space: nowrap;
        cursor: pointer;
        -webkit-appearance: none;
        text-align: center;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        outline: 0;
        -webkit-transition: .1s;
        transition: .1s;
        font-weight: 500;
        padding: 8px 15px;
        font-size: 12px;
        border-radius: 3px;
        color: #fff;
        background-color: #409EFF;
        border-color: #409EFF;
        margin-right: 10px;
    }
}

.preview_canvas {
    position: absolute;
    top: 0px;
    left: 0px;
}

.handTitle {
    transform: rotate(90deg);
    flex: 1;
    color: #666;
}

.handBtn button {
    font-size: 28rpx;
}

.handBtn {
    width: 100%;
    height: 95vh;
    display: flex;
    justify-content: space-between;
    align-content: space-between;
    flex: 1;
}

.delBtn {
    position: absolute;
    top: 250rpx;
    left: 0rpx;
    transform: rotate(90deg);
    color: #666;
}

.subBtn {
    display: inline-flex;
    transform: rotate(90deg);
    background: #008ef6;
    color: #fff;
    margin-bottom: 30rpx;
    text-align: center;
    justify-content: center;
}

/*Peach - 新增 - 保存*/

.saveBtn {
    transform: rotate(90deg);
    color: #666;
}

.previewBtn {
    transform: rotate(90deg);
    color: #666;
}

.uploadBtn {
    transform: rotate(90deg);
    color: #666;
}

/*Peach - 新增 - 保存*/

.black-select {
    top: 30rpx;
    left: 25rpx;
}

.black-select.color_select {
    width: 60rpx;
    height: 60rpx;
}

.red-select {
    width: 60rpx;
    height: 60rpx;
}

.red-select.color_select {
    width: 60rpx;
    height: 60rpx;
}

.colorwarp {
    width: 100%;
    height: 150rpx;
    display: flex;
    align-items: flex-start;

    image {
        width: 60rpx;
        height: 60rpx;
    }
}

.warp {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    view {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 20%;
        height: 80rpx;
        background-color: #008ef6;
        color: #fff;
    }
}
</style>